<template>
  <div class="component-root-container flex">
    <el-header>
      <el-form ref="theLogRule" :rules="theLogRule" :model="theLog" label-position="right" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="场景名称:" prop="scene">
              <el-select v-model="theLog['scene']" placeholder="请选择场景" class="multiple-select" multiple clearable>
                <el-option v-for="item in sceneTypes" :key="item.key" :label="item.value" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="选择时间:" prop="dateTime">
              <el-date-picker v-model="theLog['dateTime']" type="daterange" :picker-options="pickerOptions"
                align="center" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="日志类型:" prop="type">
              <el-select v-model="theLog['type']" placeholder="请选择日志类型" clearable>
                <el-option v-for="item in logTypes" :key="item.key" :label="item.value" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关键字:" prop="keyword">
              <el-input v-model="theLog['keyword']" placeholder="请输入日志查询关键字" @input="change($event)" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="8" class="col_button">
            <div class="button">
              <el-button class="query" @click="buttonClick">
                查询
              </el-button>
              <el-button class="query" @click="reset">
                重置
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-header>
    <el-main>
      <el-row :gutter="15" class="ml-time-row">
        <!-- <el-col :span="12">
            时间范围: {{ theLog['dateTime'].length > 0 ? dateFormat(theLog['dateTime'][0]) + '至' + dateFormat(theLog['dateTime'][1]) : '' }}
          </el-col> -->
        <el-col :span="12">
          用时{{usedTime}}秒，共找到{{logCounts}}条日志
        </el-col>
      </el-row>
      <el-row class="chart-container">
        <IEcharts :option="chartOptions" :loading="loading" :resizable="resizable" />
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12" class="log-detail-color">
          日志详情展示
        </el-col>
        <el-col :span="12" align="right">
          <span v-if="desc" @click="toggleDesc"><i class="el-icon-sort-down"></i>降序排序</span>
          <span v-else @click="toggleDesc"> <i class="el-icon-sort-up"></i>升序排序</span>
        </el-col>
      </el-row>
      <el-table height="500" v-loading="logListLoading" ref="logTable" border :data="logDataByTime" class="table-bottom"
        element-loading-text="数据加载中...">
        <el-table-column prop="createTime" align="center" label="创建时间" width="150">
        </el-table-column>
        <el-table-column prop="logId" align="center" label="日志ID" width="180" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="reqId" align="center" label="请求ID" width="180" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="scene" align="center" label="日志场景" width="100" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="logType" align="center" label="日志类型" width="100">
        </el-table-column>
        <el-table-column prop="logLevel" align="center" label="日志级别" width="100">
        </el-table-column>
        <el-table-column prop="logData" align="center" label="日志数据">
        </el-table-column>
        <!--<el-table-column
          prop="message"
          align="center"
          label="日志信息"
        >
        </el-table-column>
        <el-table-column
          prop="count"
          align="center"
          label="该日期日志数量"
          show-overflow-tooltip
       >
        </el-table-column>-->
      </el-table>
      <el-row>
        <el-col :span="24">
          <el-pagination :page-sizes="[5, 10, 25, 50]" :current-page="paginationData['currentPage']" :page-size="paginationData['pageSize']"
            :total="paginationData['total']" layout="prev, pager, next" @current-change="currentChange" @size-change="handleSizeChange" />
        </el-col>
      </el-row>
    </el-main>
  </div>
</template>

<script>
  import IEcharts from 'vue-echarts-v3/src/full.js'

  export default {
    components: {
      IEcharts
    },
    data() {
      return {
        listLoading: false,
        logListLoading: false,
        theLog: {
          scene: '',
          type: '',
          keyword: '',
          dateTime: []
        },
        resizable: true,
        usedTime: 0,
        logCounts: 0,
        sceneTypes: [{
            key: '1.1',
            value: '项目状态实时获取'
          },
          {
            key: '1.2',
            value: '采购、入库、付款单据匹配检查'
          },
          {
            key: '1.3',
            value: '工程物资一致性检查'
          },
          {
            key: '1.4',
            value: '物资参考价提示'
          },
          {
            key: '1.5',
            value: '产品与资源一致性检查'
          },
          {
            key: '1.6',
            value: '站址周边场租水平提示'
          },
          {
            key: '2.2',
            value: '订单打标业务状态查询'
          },
          {
            key: '2.3',
            value: '固化数据绑定订单查询'
          },
          {
            key: '2.5',
            value: '订单起租不及时风险校验'
          },
          {
            key: '2.6',
            value: '资源打标业务状态查询'
          },
          {
            key: '2.7',
            value: '集中操作关联查询展示'
          },
          {
            key: '2.8',
            value: '场地费(场地租金)自动稽核'
          },
          {
            key: '2.9',
            value: '客户提前退租的赔偿金额校验'
          },
          {
            key: '2.10',
            value: '铁塔信息变更合规性校验'
          },
          {
            key: '2.11',
            value: '机房信息变更合规性校验'
          },
          {
            key: '2.12',
            value: '拆站合规性校验'
          },
          {
            key: '2.13',
            value: '长期无法服务合规性校验'
          },
          {
            key: '2.14',
            value: '存量历史站交割合规性校验'
          },
          {
            key: '2.15',
            value: '场地费（一次性进场费及协调费）合规性校验'
          },
          {
            key: '2.16',
            value: '场地费（土地征用费）变更合规性校验'
          },
          {
            key: '2.17',
            value: '天线挂高变更合规性校验'
          },
          {
            key: '2.18',
            value: '塔类首家租户判断检查'
          },
          {
            key: '2.19',
            value: '场地费共享合规性校验'
          },
          {
            key: '2.20',
            value: '是否更新为标准建造成本合规性校验'
          },
          {
            key: '2.21',
            value: 'RRU上塔合规性校验'
          },
          {
            key: '2.22',
            value: '风压变更合规性校验'
          },
          {
            key: '2.23',
            value: 'RRU机房信息变更合规性校验'
          },
          {
            key: '2.25',
            value: '订单费用追溯合规性校验'
          }
          ,
          {
            key: '2.26',
            value: '结算报账发起合规性校验'
          },
          {
            key: '3.10',
            value: '站址拆站信息实时提示'
          },
          {
            key: '3.11',
            value: '资源资产查询'
          },{
            
            key: '3.12',
            value: '一码到底全生命周期监控'
          },
          {
            key: '3.9',
            value: '资产信息校验查询'
          },
          {
            key: '3.2',
            value: '合同校验规则前置'
          },
          {
            key: '3.3',
            value: '业主信息一致性校验'
          },
          {
            key: '3.4',
            value: '非塔类订单绑定资源合规性校验'
          }
          ,
          {
            key: '3.140',
            value: '一码到底全流程溯源-基础信息'
          },
          {
            key: '3.141',
            value: '一码到底全流程溯源-采购信息'
          },
          {
            key: '3.142',
            value: '一码到底全流程溯源-资产信息'
          },
          {
            key: '3.143',
            value: '一码到底全流程溯源-资产报废'
          },
          {
            key: '3.144',
            value: '一码到底全流程溯源-出入库信息'
          },
          {
            key: '3.145',
            value: '一码到底全流程溯源-项目信息'
          },
          {
            key: '3.146',
            value: '一码到底全流程溯源-调拨信息'
          }
          ,
          {
            key: '2.1',
            value: '采购支付风险防控'
          }
          ,
          {
            key: '4.1',
            value: '起租前同一个订单关联站址状态和挂高等基础信息一致性校验'
          }
          
        ],
        logTypes: [{
            key: 1,
            value: '全部日志'
          },
          {
            key: 0,
            value: '入参日志'
          },
          {
            key: 2,
            value: '返回日志'
          }
        ],
        paginationData: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        loading: false,
        desc: true,
        logCountsByTime: [],
        logDataByTime: [],
        pickerOptions: {
          shortcuts: [{
              text: '最近一周',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                picker.$emit('pick', [start, end])
              }
            }
          ]
        },
        theLogRule: {
          scene: [{
            required: true,
            message: '请选择场景',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '请选择日志类型',
            trigger: 'blur,change'
          }],
          dateTime: [{
            required: true,
            message: '请选择时间',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      // this.setDefaultTime()
    },
    mounted() {},
    computed: {
      chartOptions() {
        return {
          title: {
            x: 'left',
            text: '调用次数条形图',
            textStyle: {
              color: '#333',
              fontSize: 16
            }
          },
          tooltip: {
            show: true, // 是否显示提示框，默认为true
            trigger: 'item', // 数据项图形触发
            axisPointer: { // 指示样式
              type: 'shadow',
              axis: 'auto'
            },
            padding: 5,
            textStyle: { // 提示框内容的样式
              color: '#fff'
            }
          },
          toolbox: {
            show: true,
            right: 30,
            feature: {
              restore: {},
              saveAsImage: {},
              magicType: {
                show: true,
                type: ['bar', 'line']
              }
            }
          },
          xAxis: {
            name: '日期',
            data: this.logCountsByTime.map(t => t.createTime)
          },
          yAxis: {
            name: '次数',
            type: 'value'
          },
          legend: {
            x: 'center',
            y: 'bottom',
            data: ['调用次数']
          },
          grid: {
            top: '55px',
            left: '20px',
            right: '80px',
            bottom: '25px',
            containLabel: true
          },
          series: [{
            name: '调用次数',
            type: 'bar',
            barMaxWidth: 30,
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#666',
                    fontSize: 10
                  },
                  formatter: function(p) {
                    let value = ''
                    if (p.value > 0) {
                      value = p.value
                      if (value > 999) {
                        let parts = value.toString().split('.')
                        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                        value = parts.join('.')
                      }
                    }
                    return value
                  }
                }
              }
            },
            data: this.logCountsByTime.map(t => t.count)
          }]
        }
      }
    },
    methods: {
      setDefaultTime() {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        this.theLog.dateTime = [start, end]
        this.getLogChart(this.dateFormat(start), this.dateFormat(end))
      },
      dateFormat(date) {
        const timeDate = new Date(date)
        const timeDateString = timeDate.toJSON()
        return timeDateString.replace('T', ' ').slice(0, 19)
      },
      // 分页跳转
      currentChange(targetPage) {
        this.paginationData['currentPage'] = targetPage
        // table数据接口
        this.buttonClick()
      },
      // 分页跳转
      handleSizeChange(size) {
        this.paginationData['pageSize'] = size
        this.paginationData['currentPage'] = 1
        // table数据接口
        this.buttonClick()
      },
      toggleDesc() {
        this.desc = !this.desc
        this.paginationData['currentPage'] = 1
        this.buttonClick()
      },
      async getLogChart(start, end, scene, type, keyword) {
        const data = {
          type: type === 1 ? '' : type,
          scene: scene,
          startTime: start,
          endTime: end,
          keyword: keyword
        }
        const r = await this.$http({
          url: this.$http.adornBizUrl('/log/search/count'),
          method: 'post',
          data: this.$http.adornData('param=' + JSON.stringify(data), false),
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        })
        if (r.data.data) {
          this.logCountsByTime = r.data.data.data.logCounts.sort((a, b) => new Date(a.createTime).getTime() - new Date(
            b.createTime).getTime())
          this.logCounts = r.data.data.data.totalCount || '0'
          this.paginationData.total = this.logCounts
        }
      },
      async buttonClick(e) {
        if (e) {
          this.paginationData['currentPage'] = 1
        }

        try {
          this.logCountsByTime = []
          this.logDataByTime = []
          this.usedTime = 0
          this.logCounts = 0
          await this.$refs['theLogRule'].validate()
          const startTime = new Date()
          const data = {
            type: this.theLog['type'] === 1 ? '' : this.theLog['type'],
            scene: this.theLog['scene'],
            keyword: this.theLog['keyword'],
            startTime: this.theLog['dateTime'][0] + ' 00:00:00',
            endTime: this.theLog['dateTime'][1] + ' 23:59:59',
            limit: this.paginationData.pageSize,
            page: this.paginationData.currentPage,
            desc: this.desc
          }
          this.getLogChart(data.startTime, data.endTime, data.scene, data.type, data.keyword)
          this.logListLoading = true
          const r = await this.$http({
            url: this.$http.adornBizUrl('/log/search/data'),
            method: 'post',
            data: this.$http.adornData('param=' + JSON.stringify(data), false),
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
          })
          if (r.data.data) {
            const endTime = new Date()
            this.usedTime = Math.round(endTime.getTime() - startTime.getTime()) / 1000
            this.logListLoading = false
            this.logDataByTime = r.data.data.data
            //this.paginationData.total = this.paginationData.pageSize * this.paginationData.currentPage + 1
            //this.logCounts = r.data.data.data.length
          }
          this.listLoading = false
        } catch (e) {
          console.log(e)
          this.listLoading = false
        } finally {
          this.listLoading = false
        }
      },
      reset() {
        this.theLog = {
          scene: '',
          type: '',
          keyword: '',
          dateTime: []
        }

        this.paginationData = {
          currentPage: 1,
          pageSize: 10,
          total: 0
        }

        this.logCountsByTime = []
        this.logDataByTime = []
        this.usedTime = 0
        this.logCounts = 0
        this.$refs['theLogRule'].clearValidate()
      },
      change(e) {
        this.$forceUpdate()
      }
    }
  }
</script>

<style scoped lang="scss">
  @import "../../../assets/scss/_formatQueryPage";
  @include formatQueryPage(0, 60%, left);
  .flex {
    display: flex;
    flex-direction: column;
  }

  .el-select, .el-input, .el-date-editor {
    width: 60%;
  }

  .chart-container {
    width: 100%;
    height: 350px;
    border: 1px solid #ececec;
    margin: 20px 0;
    padding: 10px 0;
  }

  .query {
    color: rgba(255, 255, 255, 1);
    background: rgba(235, 75, 75, 1);
    border-radius: 6px;
  }

  .log-detail-color {
    font-size: 16px;
    color: rgba(51, 51, 51, 1);
    font-weight: bold;
  }
</style>
